package controllers

import (
	"context"
	beego "github.com/beego/beego/v2/server/web"
	"gorm.io/gorm"
	"shang/models"
	"strconv"
)

type BroadcastController struct {
	beego.Controller
}

func (b *BroadcastController) CreateBroadcast() {
	AnchorName := b.GetString("anchor")
	push := "rtmp://127.0.0.1/mylive"
	sowing := "http://127.0.0.1/hLive/demo.html"
	_, err := models.CreateAnchor(models.BroadCast{
		AnchorName:    AnchorName,
		PushMessage:   push,
		SowingMessage: sowing,
	})
	if err != nil {
		b.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "创建直播间失败",
		}
		b.ServeJSON()
		return
	}
	b.Data["json"] = map[string]interface{}{
		"code": 200,
		"msg":  "直播间创建创建成功",
	}
	b.ServeJSON()
}

func (b *BroadcastController) LookBroadcast() {
	userid := b.GetString("userid")
	anchorid := b.GetString("anchor")
	exists := models.Redis.Exists(context.Background(), anchorid+"blacklist:"+userid).Val()
	if exists != 0 {
		b.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "你已经被对方拉进黑名单",
		}
		b.ServeJSON()
		return
	}
	id, _ := strconv.Atoi(anchorid)
	broadcast, _ := models.GetAnchor(models.BroadCast{
		Model: gorm.Model{ID: uint(id)},
	})
	if broadcast.ID == 0 {
		b.Data["json"] = map[string]interface{}{
			"code": 400,
			"msg":  "主播不存在",
		}
		b.ServeJSON()
		return
	}
	b.Data["json"] = map[string]interface{}{
		"code":   200,
		"msg":    "打开浏览器进入直播间",
		"sowing": broadcast.SowingMessage,
	}
	b.ServeJSON()
}
